package com.shievy.anweb.webview.web.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.shievy.anweb.base.uitl.LogUtil;
import com.shievy.anweb.webview.entry.JsParams;
import com.shievy.anweb.webview.web.callback.WebViewCallBack;
import com.shievy.anweb.webview.web.dispatch.WebDispatcher;
import com.shievy.anweb.webview.web.setting.WebViewSetting;
import com.shievy.anweb.webview.web.chrome.XWebChromeClient;
import com.shievy.anweb.webview.web.client.XWebViewClient;

import java.util.Map;
import java.util.Objects;

/**
 * 自定义WebView
 */
public class BaseWebView extends WebView {

    private Gson gson;

    public BaseWebView(@NonNull Context context) {
        super(context);
        initConfig();
    }

    public BaseWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public BaseWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public BaseWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initConfig();
    }

    /**
     * 初始化配置
     */
    @SuppressLint("JavascriptInterface")
    private void initConfig() {
        WebViewSetting.INSTANCE.configDefaultSetting(this);
        addJavascriptInterface(this, "android");
        WebDispatcher.Companion.getWebTelecomService().createConnection(getContext().getApplicationContext());
    }

    public Gson getGson() {
        if (gson == null) {
            gson = new GsonBuilder().create();
        }
        return gson;
    }

    /**
     * 注册回调
     */
    public void registerWebViewCallBack(WebViewCallBack callBack) {
        setWebChromeClient(new XWebChromeClient(callBack));
        setWebViewClient(new XWebViewClient(callBack));
    }

    /**
     * 通用 js 调用 java方法
     */

    @JavascriptInterface
    public void takeNativeAction(String jsParam) {
        LogUtil.INSTANCE.i("takeNativeAction ==> ", jsParam);
        Map jsParams = getGson().fromJson(jsParam, Map.class);
        if (jsParams != null) {
            String telecomID = String.valueOf(jsParams.get("telecomID"));
            String params = getGson().toJson(jsParams.get("params"));
            Object jsMethodID = jsParams.get("jsMethodID");
            Objects.requireNonNull(WebDispatcher.Companion.getWebTelecomService()).callNativeMain(telecomID, params, (jsMethodID == null) ? "" : jsMethodID.toString(), this);
        }
    }

    /**
     * 原生调用 JS
     */
    public void takeJsAction(String jsMethodID, String param) {
        post(() -> {
            String result = "";
            if (isJson(param)) {
                result = "javascript:xweb.callback('" + jsMethodID + "'," + param + ")";
            } else {
                result = "javascript:xweb.callback('" + jsMethodID + "','" + param + "')";
            }
            LogUtil.INSTANCE.e("takeJsAction == >", result);
            evaluateJavascript(result, null);
        });
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        WebDispatcher.Companion.getWebTelecomService().unBind();
    }

    private boolean isJson(String str) {
        try {
            new Gson().fromJson(str, Object.class);
            return true;
        } catch (JsonSyntaxException e) {
            return false;
        }
    }
}
